﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Text;

namespace SimpleIpc
{
    public abstract class AbstractRemoteChannel : IRemoteChannel
    {
        protected IChannel channel;
        public abstract string Name { get; }

        public virtual T GetObject<T>(string uri)
        {
            return (T)Activator.GetObject(typeof(T), uri);
        }

        public virtual void RegisterWellKnownService<T>(string uri)
            where T : new()
        {
            RegisterWellKnownService<T>(uri, WellKnownObjectMode.Singleton);
        }

        public virtual void RegisterWellKnownService<T>(string uri, WellKnownObjectMode mode)
            where T : new()
        {
            RegisterWellKnownService(typeof(T), uri, mode);
        }

        public virtual void RegisterWellKnownService(Type type, string uri, WellKnownObjectMode mode)
        {
            RemotingConfiguration.RegisterWellKnownServiceType(type, uri, mode);
        }

        public void RegisterChannel()
        {
            if (channel == null)
                return;
            RemoteChannelFactory.AddChannel(this);
            try
            {
                ChannelServices.RegisterChannel(channel, false);
            }
            catch
            {
                throw;
            }
        }

        public void UnregisterChannel()
        {
            if (channel == null)
                return;
            RemoteChannelFactory.RemoveChannel(this);
            try
            {
                ChannelServices.UnregisterChannel(channel);
            }
            catch
            {
                throw;
            }
        }
    }
}
